﻿using AutoMapper;
using BackData;
using Domain.Quality;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Equipment;

namespace Team.API.Applocation.Hanldler.Equipment
{
    /// <summary>
    /// 设备更新命令处理器
    /// 实现MediatR的IRequestHandler接口，用于处理设备更新逻辑，返回包含更新结果的APIResult
    /// </summary>
    public class UpdateEquipmentHandler : IRequestHandler<UpdateEquipmentCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Equipmentmodel> equiRep;

        /// <summary>
        /// 构造函数，注入依赖服务
        /// </summary>
        /// <param name="mapper">AutoMapper 实例，用于对象映射</param>
        /// <param name="equiRep">设备仓储接口，封装数据访问逻辑</param>
        public UpdateEquipmentHandler(IMapper mapper, IRepository<Equipmentmodel> equiRep)
        {
            this.mapper = mapper;
            this.equiRep = equiRep;
        }

        /// <summary>
        /// 处理设备更新的核心方法
        /// 从仓储获取设备、映射更新数据、执行更新并返回结果
        /// </summary>
        /// <param name="request">设备更新命令，包含待更新设备的ID及更新数据</param>
        /// <param name="cancellationToken">用于异步操作取消的令牌</param>
        /// <returns>包含更新结果、状态码和提示信息的APIResult</returns>
        public async Task<APIResult<int>> Handle(UpdateEquipmentCommand request, CancellationToken cancellationToken)
        {
            // 从仓储获取待更新的设备实体
            var equipment = await equiRep.GetByIdAsync(request.Id);
            if (equipment == null)
            {
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "设备不存在",
                    Result = 0
                };
            }
            // 将命令中的更新数据映射到设备实体
            var result=  mapper.Map<Equipmentmodel>(request);

            // 执行更新操作
            var r= await equiRep.UpdateAsync(result);

            if (r > 0)
            {
                // 返回更新成功的结果
                return new APIResult<int>
                {
                    Code = StateCode.OK,
                    Message = "设备更新成功",
                    Result =r
                };
            }
            else
            {
                // 返回更新失败的结果
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "设备更新失败",
                    Result =r
                };
            }
        }
    }
}
